<template>
  <el-button text @click="isShow = !isShow" :bg="isShow" :type="isShow ? 'primary' : ''">
    实时路况
  </el-button>
</template>

<script setup>
import { ref, watch } from 'vue'

let queryResultLayer

const { map } = defineProps({
  map: {
    type: Object,
    required: true,
  },
})
const isShow = ref(false)

//封装查询功能
const attQuery = () => {
  // 调用封装的函数清除之前的查询结果
  clearA()
  // 参数结构对象
  const queryStruct = new Zondy.Service.QueryFeatureStruct({
    IncludeGeometry: true, //是否包含几何信息
  })

  // 查询参数信息对象
  const queryParam = new Zondy.Service.QueryByLayerParameter(
    'gdbp://MapGisLocal/wuhan/sfcls/武汉光谷道路',
    {
      struct: queryStruct,
    },
  )

  // 实例化矢量图层查询服务对象
  const queryService = new Zondy.Service.QueryLayerFeature(queryParam, {
    ip: '127.0.0.1',
    port: '8089',
  })
  // 执行查询操作，querySuccess为查询回调函数
  queryService.query(querySuccess, queryError)
}
// 查询失败回调
const queryError = (e) => {
  console.log(e)
}
// 查询成功回调
const querySuccess = (result) => {
  // 初始化Zondy.Format.PolygonJSON类
  const format = new Zondy.Format.PolygonJSON()
  // 将MapGIS要素JSON反序列化为ol.Feature类型数组
  const features = format.read(result)
  // 实例化一个矢量图层queryResultLayer用于显示查询结果
  queryResultLayer = new ol.layer.Vector({})
  // 设置矢量图层数据源
  const queryResultSource = new ol.source.Vector({
    features,
    wrapX: false,
  })
  queryResultLayer.setSource(queryResultSource)
  // 设置样式
  const style = (f) => {
    const flow = f.getProperties().get('车流量')
    const color = flow < 1000 ? 'green' : flow < 1500 ? 'yellow' : 'red'
    return new ol.style.Style({
      stroke: new ol.style.Stroke({
        color,
        width: 10,
      }),
    })
  }
  queryResultLayer.setStyle(style)
  // 显示图层
  map.addLayer(queryResultLayer)
}
// 封装清除查询结果功能
const clearA = () => {
  if (queryResultLayer) {
    map.removeLayer(queryResultLayer)
    queryResultLayer = null
  }
}

watch(isShow, () => {
  if (isShow.value) attQuery()
  else clearA()
})
</script>

<style scoped></style>
